import Footer from '@/components/Footer';
import { userLoginUsingPost } from '@/services/backend/userController';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { LoginForm, ProFormText } from '@ant-design/pro-components';
import { useEmotionCss } from '@ant-design/use-emotion-css';
import { Helmet, history, useModel } from '@umijs/max';
import { message } from 'antd';
import React, { useState } from 'react';
import Settings from '../../../../config/defaultSettings';
import md5 from 'md5';

import './index.css';

const Login: React.FC = () => {
  const [type, setType] = useState<string>('account');
  const { initialState, setInitialState } = useModel('@@initialState');
  const containerClassName = useEmotionCss(() => {
    return {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      backgroundImage: 'url(/background.jpg)',
      backgroundSize: '100% 100%',
    };
  });

  const handleSubmit = async (values: API.UserLoginRequest) => {
    try {
      // 登录
      if (!values.userAccount || !values.userPassword) {
        message.error('User name and password cannot be empty');
        return;
      }
      const encryptPassword = md5(values.userPassword).toUpperCase();
      const res = await userLoginUsingPost({
        ...values,
        userPassword: encryptPassword as string,
      });

      const defaultLoginSuccessMessage = 'Login successful!';
      message.success(defaultLoginSuccessMessage);
      // 保存已登录用户信息
      setInitialState({
        ...initialState,
        currentUser: res.data,
      });
      const urlParams = new URL(window.location.href).searchParams;
      history.push(urlParams.get('redirect') || '/');
      return;
    } catch (error: any) {
      const defaultLoginFailureMessage = `Login failed,${error.message}`;
      message.error(defaultLoginFailureMessage);
    }
  };

  return (
    <div
      className={containerClassName}
      style={{
        flex: '1',
        padding: '32px 0',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
      }}
    >
      <Helmet>
        <title>
          {'Login'}- {Settings.title}
        </title>
      </Helmet>
      <div
        style={{
          flex: '1',
          padding: '32px 0',
          display: 'flex', // 使用Flexbox布局
          justifyContent: 'center', // 水平居中
          alignItems: 'center', // 垂直居中
        }}
      >
        <div
          style={{
            flex: '1',
            padding: '32px 0',
          }}
        >
          <div style={{ position: 'absolute', top: 0, left: 0, margin: '16px' }}>
            <img alt="logo" style={{ height: '40px' }} src="/dynabook.png" />
          </div>
          <LoginForm
            contentStyle={{
              minWidth: 280,
              maxWidth: '75vw',
            }}
            // logo={<img alt="logo" style={{ height: '100%' }} src="/logo.svg" />}
            title="dynaEnergy"
            initialValues={{
              autoLogin: true,
            }}
            submitter={{
              searchConfig: {
                submitText: 'Login',
              },
            }}
            onFinish={async (values) => {
              await handleSubmit(values as API.UserLoginRequest);
            }}
          >
            {/* <div
              style={{
                textAlign: 'center',
                marginTop: '0px',
                marginBottom: '20px',
                fontSize: '15px',
              }}
            >
              Deployment Assistant
            </div> */}
            {type === 'account' && (
              <>
                <ProFormText
                  name="userAccount"
                  fieldProps={{
                    size: 'large',
                    prefix: <UserOutlined />,
                  }}
                  placeholder={'Please input your account'}
                  rules={[
                    {
                      required: true,
                      message: 'Account number is required!',
                    },
                  ]}
                />
                <ProFormText.Password
                  name="userPassword"
                  fieldProps={{
                    size: 'large',
                    prefix: <LockOutlined />,
                  }}
                  placeholder={'Please input your password'}
                  rules={[
                    {
                      required: true,
                      message: 'Password is required!',
                    },
                  ]}
                />
              </>
            )}

            <div
              style={{
                marginBottom: 24,
                textAlign: 'right',
              }}
            >
              {/* <Link to="/user/register">新用户注册</Link> */}
            </div>
          </LoginForm>
        </div>
      </div>
      <Footer />
    </div>
  );
};
export default Login;
